package com.xwy.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xwy.usercenter.common.BaseResponse;
import com.xwy.usercenter.common.ErrorCode;
import com.xwy.usercenter.common.ResultUtils;
import com.xwy.usercenter.exception.BusinessException;
import com.xwy.usercenter.mapper.UserMapper;
import com.xwy.usercenter.model.User;
import com.xwy.usercenter.model.vo.UserVO;
import com.xwy.usercenter.service.UserService;

import com.xwy.usercenter.utils.AlgorithmUtils;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.xwy.usercenter.utils.RedisConstants.CPMATCH_USER_RECOMMEND;
import static com.xwy.usercenter.utils.SystemConstants.*;


/**
 * 用户服务
 *
 * @author xwy
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Long userRegister(String userAccount, String userPassword, String checkPassword, String plantCode){
        //1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, plantCode)){
            throw new BusinessException(ErrorCode.NULL_ERROR, "参数为空");
        }
        //TODO
        //2.校验长度
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (plantCode.length() > 5){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }

        //校验账户不含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\\\\\[\\\\\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);

        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号含特殊字符");
        }
        if (!userPassword.equals(checkPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "第二次密码错误");
        }

        //判断账户是否重复（应该放在最后，如果前面的校验不通过，我们就省去了一次查询数据库的浪费）
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAccount, userAccount);
        int count = this.count(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在");
        }

        //判断星球编号是否重复
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPlanetCode, plantCode);
        count = this.count(queryWrapper);
        if (count > 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号重复");
        }

        //2.加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //3.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(plantCode);
        this.save(user);
        return user.getId();
    }

    @Override
    public User login(String userAccount, String userPassword, HttpServletRequest request) {
        //1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.NULL_ERROR, "输入参数为空");
        }

        //2.校验长度
        if (userAccount.length() < 4){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }

        //校验账户不含特殊字符
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\\\\\[\\\\\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        //如果发现了含特殊字符，返回错误信息
        if (matcher.find()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号存在特殊字符");
        }

        //2.加密
        String encryptPassword =
                DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //判断账户是否重复（应该放在最后，如果前面的校验不通过，我们就省去了一次查询数据库的浪费）
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserPassword, encryptPassword)
                .eq(User::getUserAccount, userAccount);
        User user = this.getOne(queryWrapper);
        //用户不存在
        if (user == null){
            log.info("User login failed, userAccount connot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号不存在");
        }
        //3.用户脱敏
        User safetyUser = safetyUser(user);
        //4.记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATUS, user);

        return safetyUser;
    }

    @Override
    public BaseResponse<Integer> logout(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATUS);
        return ResultUtils.success(1);

    }

    /**
     * 内存查询
     * @param tagsLists
     * @return
     */
    @Override
    public List<User> searchUsersBytags(List<String> tagsLists){
        if (CollectionUtils.isEmpty(tagsLists)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //内存查询，在内存中判断是否包含符合要求的tag。将所有用户数据从数据库中取出来，然后再在内存
        //中进行筛选，过滤
        List<User> userList = list();
        Gson gson = new Gson();
        //使用Gson进行反序列化，将json串转成String字符串。使用filter将每个user进行过滤，
        //取出tag，后面再看看这段
        List<User> safetyUsers = userList.stream().filter(user -> {
            String tagStr = user.getTags();
            if (tagStr == null) {
                return false;
            }
            //gson转集合使用typeToken
            Set<String> tempTagNameSet = gson.fromJson(tagStr, new TypeToken<Set<String>>() {
            }.getType());
            //利用optional来判读NPE问题
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tagName : tagsLists) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::safetyUser).collect(Collectors.toList());
        return safetyUsers;
    }

    /**
     * 使用and拼接查询(sql，已过时)
     * @param tagsLists
     * @return
     */
    @Deprecated  //表示该方法已过时
    @Override
    public List<User> searchUsersBytagsBySql(List<String> tagsLists){
        if (CollectionUtils.isEmpty(tagsLists)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //使用and拼接查询
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        for (String tag : tagsLists) {
            queryWrapper = queryWrapper.like(User::getTags, tag);
        }
        List<User> list = this.list(queryWrapper);
        return list.stream().map(this::safetyUser).collect(Collectors.toList());
    }

    @Override
    public Integer updateUser(User user, User loginUser) {
        Long userId = user.getId();
        if (userId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //TODO 补充校验，如果用户没有传入任何需要修改的值，就直接报错，不用运行sql语句

        //若不是管理员也不是本人，无权修改
        if (!(isAdmin(loginUser)) && !userId.equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //是管理员或者是本人，可以进行修改
        User oldUser = getById(userId);
        if (oldUser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return userMapper.updateById(user);
    }

    @Override
    public Page<User> recommendUser(Long pageSize, Long pageNum, HttpServletRequest request) {
        User loginUser = getLoginUser(request);
        String redisKey = CPMATCH_USER_RECOMMEND + loginUser.getId();
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        Page<User> userPage = (Page<User>) valueOperations.get(redisKey);
        if (userPage != null){
            return userPage;
        }
        //无缓存，查数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        userPage = page(new Page<>(pageNum, pageSize), queryWrapper);

        //无缓存则写缓存
        //为什么要try catch？如果写缓存写失败了，还是要把从数据库查询出来的数据传给前端
        //如果直接抛出异常了，给到前端的数据就是错误的
        try {
            valueOperations.set(redisKey, userPage, 3, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return userPage;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        User loginUser = (User) request.getSession().getAttribute(USER_LOGIN_STATUS);
        if (loginUser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return loginUser;
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        return getLoginUser(request).getUserRole() == ADMIN_ROLE;
    }

    @Override
    public boolean isAdmin(User loginUser) {
        return loginUser.getUserRole() == ADMIN_ROLE;
    }

    /**
     * 推荐匹配用户
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNotNull("tags");
        queryWrapper.select("id","tags");
        List<User> userList = this.list(queryWrapper);

        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());
        // 用户列表的下表 => 相似度'
        List<Pair<User,Long>> list = new ArrayList<>();
        // 依次计算当前用户和所有用户的相似度
        for (int i = 0; i <userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            //无标签的 或当前用户为自己
            if (StringUtils.isBlank(userTags) || user.getId() == loginUser.getId()){
                continue;
            }
            List<String> userTagList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());
            //计算分数
            long distance = AlgorithmUtils.minDistance(tagList, userTagList);
            list.add(new Pair<>(user,distance));
        }
        //按编辑距离有小到大排序
        List<Pair<User, Long>> topUserPairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num)
                .collect(Collectors.toList());
        //有顺序的userID列表
        List<Long> userListVo = topUserPairList.stream().map(pari -> pari.getKey().getId()).collect(Collectors.toList());

        //根据id查询user完整信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id",userListVo);
        Map<Long, List<User>> userIdUserListMap = this.list(userQueryWrapper).stream()
                .map(user -> safetyUser(user))
                .collect(Collectors.groupingBy(User::getId));

        // 因为上面查询打乱了顺序，这里根据上面有序的userID列表赋值
        List<User> finalUserList = new ArrayList<>();
        for (Long userId : userListVo){
            finalUserList.add(userIdUserListMap.get(userId).get(0));
        }
        return finalUserList;
    }


    /**
     * 返回脱敏的用户信息
     * @param user
     * @return
     */
    @Override
    public User safetyUser(User user){
        if (user == null){
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUsername(user.getUsername());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setUserStatus(user.getUserStatus());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setPlanetCode(user.getPlanetCode());
        safetyUser.setTags(user.getTags());
        safetyUser.setProfile(user.getProfile());
        return safetyUser;
    }



}




